package com.chuanjiabao.wisdom.ui.activity;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.databinding.DataBindingUtil;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.common.OSSLog;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSFederationToken;
import com.alibaba.sdk.android.oss.common.auth.OSSStsTokenCredentialProvider;
import com.chuanjiabao.wisdom.MainActivity;
import com.chuanjiabao.wisdom.R;
import com.chuanjiabao.wisdom.adapter.ApplicationState;
import com.chuanjiabao.wisdom.adapter.BaseFragmentAdapter;
import com.chuanjiabao.wisdom.application.FApplication;
import com.chuanjiabao.wisdom.bean.FamilyDeatilCallbackBean;
import com.chuanjiabao.wisdom.bean.FamilyFileTotalBean;
import com.chuanjiabao.wisdom.bean.InviteCallbackBean;
import com.chuanjiabao.wisdom.bean.RefreshMessageEvent;
import com.chuanjiabao.wisdom.bean.STSCallBackBean;
import com.chuanjiabao.wisdom.bean.UpdateFileTeam;
import com.chuanjiabao.wisdom.bean.UpdateStatus;
import com.chuanjiabao.wisdom.databinding.ActivityFamilyPeopleFilesBinding;
import com.chuanjiabao.wisdom.greendao.gen.UpdateStatusDao;
import com.chuanjiabao.wisdom.listener.OnBHClickListener;
import com.chuanjiabao.wisdom.service.UpdateService;
import com.chuanjiabao.wisdom.ui.ActivityStack;
import com.chuanjiabao.wisdom.ui.BaseActivity;
import com.chuanjiabao.wisdom.ui.fragment.FamilyPhotoFragment;
import com.chuanjiabao.wisdom.ui.fragment.FamilyTextFragment;
import com.chuanjiabao.wisdom.ui.fragment.FamilyVideoFragment;
import com.chuanjiabao.wisdom.ui.fragment.IndexFragment;
import com.chuanjiabao.wisdom.util.BHThreadPool;
import com.chuanjiabao.wisdom.util.GlideUtil;
import com.chuanjiabao.wisdom.util.GsonUtil;
import com.chuanjiabao.wisdom.util.HTTPAPI;
import com.chuanjiabao.wisdom.util.LogUtil;
import com.chuanjiabao.wisdom.util.SpResourceUtil;
import com.chuanjiabao.wisdom.util.SpUtils;
import com.chuanjiabao.wisdom.util.StringUtil;
import com.chuanjiabao.wisdom.util.TimeUtil;
import com.chuanjiabao.wisdom.util.ToastUtil;
import com.chuanjiabao.wisdom.util.dialog.ArriveDialog;
import com.chuanjiabao.wisdom.util.dialog.HintDeleteDialog;
import com.chuanjiabao.wisdom.util.dialog.JoinQueueDialog;
import com.chuanjiabao.wisdom.util.dialog.PermissionDialog;
import com.chuanjiabao.wisdom.util.dialog.ShareDialog;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.lzy.okgo.callback.StringCallback;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;

import static com.chuanjiabao.wisdom.bean.Constants.UPDATE_LOAD_HOME;

/**
 * 家人文件列表
 */
public class FamilyPeopleFilesActivity extends BaseActivity implements ViewPager.OnPageChangeListener {

    ActivityFamilyPeopleFilesBinding binding;
    String homeId, peopleId, d_id;

    List<TextView> texts = new ArrayList<>();
    List<View> views = new ArrayList<>();

    List<UpdateFileTeam> list = new ArrayList<>();

    UpdateStatusDao updateStatusDao = FApplication.getInstance().getDaoSession().getUpdateStatusDao();

    int mViewPagerCount = 3;
    Fragment[] fragment = new Fragment[3];
    private ApplicationState applicationState = new ApplicationState();

    FamilyDeatilCallbackBean.DataBean.MembersBean bean;

    OSSClient oss;

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            LogUtil.e("接收到信息");
            BaseFragmentAdapter fragmentAdapter = new BaseFragmentAdapter(getSupportFragmentManager());
            fragment[0] = new FamilyPhotoFragment(oss, homeId, peopleId);
            fragment[1] = new FamilyVideoFragment(oss, homeId, peopleId);
            fragment[2] = new FamilyTextFragment(oss, homeId, peopleId);

            fragmentAdapter.addData(fragment);
            binding.vpModule.setAdapter(fragmentAdapter);
            binding.vpModule.setCurrentItem(mViewPagerCount);
            binding.vpModule.addOnPageChangeListener(FamilyPeopleFilesActivity.this);
            changePage(0);
        }
    };

    //上传头像服务
    private Intent mServiceIntent;
    private UpdateService updateService;
    private ServiceConnection conn = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
            updateService = null;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            updateService = ((UpdateService.MyBinder) service).getService();
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        homeId = SpResourceUtil.getHomeId();
        peopleId = SpResourceUtil.getPeopleId();
        if (!TextUtils.isEmpty(homeId)) {
            getFamilyDetail();
            getHomeFileTotal();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        bindService(mServiceIntent, conn, BIND_AUTO_CREATE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(conn);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_family_people_files);
        binding.setActivity(this);
        initView();
    }

    @SuppressLint("SetTextI18n")
    private void initView() {
        setBack();

        mServiceIntent = new Intent(this, UpdateService.class);
        IntentFilter mIntentFilter = new IntentFilter();
        mIntentFilter.addAction(UpdateService.HEART_BEAT_ACTION);
        mIntentFilter.addAction(UpdateService.MESSAGE_ACTION);

        if (oss == null) {
            getSTS();
        }

        texts.add(binding.tvModulePhoto);
        texts.add(binding.tvModuleVideo);
        texts.add(binding.tvModuleText);

        views.add(binding.viewModulePhoto);
        views.add(binding.viewModuleVideo);
        views.add(binding.viewModuleText);

        binding.tvModuleEdit.setOnClickListener(this);
        binding.llModulePhoto.setOnClickListener(this);
        binding.llModuleVideo.setOnClickListener(this);
        binding.llModuleText.setOnClickListener(this);
        binding.llModuleDelete.setOnClickListener(this);
        binding.tvModuleSelect.setOnClickListener(this);
        binding.llModuleCallPhone.setOnClickListener(this);
        binding.llModulePhone.setOnClickListener(this);
        findViewById(R.id.rightImage).setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rightImage:
                ArriveDialog arriveDialog = new ArriveDialog(this);
                arriveDialog.show();
                arriveDialog.setOnBHClickListener(position -> {
                    RefreshMessageEvent event = new RefreshMessageEvent();
                    event.setType("main");
                    event.setId(position + "");
                    EventBus.getDefault().post(event);
                    ActivityStack.getScreenManager().popAllActivityExceptOne(MainActivity.class);
                });
                break;
            case R.id.llModuleCallPhone:
                if (!TextUtils.equals("1", IndexFragment.permissionsId)
                        && !TextUtils.equals("4", IndexFragment.permissionsId)) {
                    showPermissionDialog();
                    return;
                }

                if (!TextUtils.isEmpty(d_id)) {
                    startInvita(d_id);
                }
                break;
            case R.id.tvModuleSelect:
                if (!TextUtils.equals("1", IndexFragment.permissionsId)
                        && !TextUtils.equals("4", IndexFragment.permissionsId)) {
                    showPermissionDialog();
                    return;
                }

                Intent intent = new Intent(this, FamilyResActivity.class);
                intent.putExtra("module_from", "people");
                intent.putExtra("module_userId", peopleId);
                switch (curret) {
                    case 0:
                        intent.putExtra("module_type", "1");
                        break;
                    case 1:
                        intent.putExtra("module_type", "2");
                        break;
                    case 2:
                        intent.putExtra("module_type", "4");
                        break;
                    default:
                }
                startActivity(intent);
                break;
            case R.id.llModuleDelete:
                if (!TextUtils.equals("1", IndexFragment.permissionsId)
                        && !TextUtils.equals("4", IndexFragment.permissionsId)) {
                    showPermissionDialog();
                    return;
                }

                new HintDeleteDialog(this)
                        .setTitle("删除家人")
                        .setContent("是否移除家人" + bean.getD_name())
                        .setYes("确认移除")
                        .setOnBHClickListener(new OnBHClickListener() {
                            @Override
                            public void onConfirmClick() {
                                UpdateStatus bean = new UpdateStatus();
                                bean.setStatus("1");
                                bean.setFirst("");
                                bean.setSecond("");
                                bean.setThird("");
                                bean.setForth("");
                                updateStatusDao.insert(bean);
                                removeHomeUser();
                            }
                        })
                        .show();
                break;
            case R.id.llModuleText:
                changePage(2);
                break;
            case R.id.llModuleVideo:
                changePage(1);
                break;
            case R.id.llModulePhoto:
                changePage(0);
                break;
            case R.id.llModulePhone:
                Intent intent2 = new Intent(
                        Intent.ACTION_DIAL,
                        Uri.parse("tel:" + binding.tvModulePhone.getText().toString())
                );
                intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent2);
                break;
            case R.id.tvModuleEdit:
                if (!TextUtils.equals("1", IndexFragment.permissionsId)
                        && !TextUtils.equals("4", IndexFragment.permissionsId)) {
                    showPermissionDialog();
                    return;
                }

                if (1 == bean.getD_is_admin()) {
                    startActivity(new Intent(FamilyPeopleFilesActivity.this, UserInfoActivity.class));
                } else {
                    Intent intentSecond = new Intent(FamilyPeopleFilesActivity.this, AddFamilyBodyActivity.class);
                    intentSecond.putExtra("module_bean", bean);
                    intentSecond.putExtra("module_funcation", "look");
                    startActivity(intentSecond);
                }
                break;
        }
    }

    private void showPermissionDialog() {
        new PermissionDialog(this)
                .setHint("对不起，您无相关操作权限")
                .show();
    }

    @SuppressLint("SetTextI18n")
    public void setActInfo(FamilyDeatilCallbackBean.DataBean.MembersBean bean) {
        try {
            if (TextUtils.isEmpty(bean.getD_head_pic())) {
                binding.tvModuleName.setVisibility(View.VISIBLE);
                binding.ivModuleHead.setVisibility(View.GONE);
                binding.tvModuleName.setText(bean.getD_name().substring(0, 1));
            } else {
                binding.ivModuleHead.setVisibility(View.VISIBLE);
                binding.tvModuleName.setVisibility(View.GONE);
                GlideUtil.setCircleMethod(this, bean.getD_head_pic(), binding.ivModuleHead);
            }

            if (1 == bean.getD_is_admin()) {
                binding.tvModuleRelation.setText("家主");
            } else {
                binding.tvModuleRelation.setText(bean.getD_relation());
            }

            if (bean.getD_birthday() == 0) {
                binding.llModuleBirthday.setVisibility(View.GONE);
                binding.llModuleYear.setVisibility(View.GONE);
            } else {
                binding.llModuleBirthday.setVisibility(View.VISIBLE);
                binding.llModuleYear.setVisibility(View.VISIBLE);
                String birth = TimeUtil.ChatToTimeStr(bean.getD_birthday());
                if (2 != bean.getD_birthday_type()) {
                    if (birth.contains("年")) {
                        binding.tvModuleBirtyday.setText("阳历." + TimeUtil.ChatToTimeStr(bean.getD_birthday()).split("年")[1]);
                    } else {
                        binding.tvModuleBirtyday.setText("阳历." + TimeUtil.ChatToTimeStr(bean.getD_birthday()));
                    }
                } else {
                    if (birth.contains("年")) {
                        binding.tvModuleBirtyday.setText("阴历." + TimeUtil.ChatToTimeStr(bean.getD_birthday()).split("年")[1]);
                    } else {
                        binding.tvModuleBirtyday.setText("阴历." + TimeUtil.ChatToTimeStr(bean.getD_birthday()));
                    }
                }
                long newTime = System.currentTimeMillis();
                binding.tvModuleYear.setText((int) (Math.ceil((newTime / 1000 - bean.getD_birthday()) / 31536000)) + "岁");
            }

            if (TextUtils.isEmpty(bean.getD_phone())) {
                binding.llModulePhone.setVisibility(View.GONE);
            } else {
                binding.tvModulePhone.setText(bean.getD_phone());
            }

            binding.setBean(bean);

            if (TextUtils.isEmpty(bean.getD_name()) && !TextUtils.isEmpty(bean.getD_relation())) {
                binding.tvModuleName.setText(bean.getD_relation().substring(0, 1));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        if (applicationState.isMainSliding() && position == 1) {
            applicationState.setMainSliding(false);
        }
        changePage(position);
    }

    @Override
    public void onPageScrollStateChanged(int state) {
        if (!applicationState.isMainSliding() && state != ViewPager.SCROLL_STATE_IDLE) {
            applicationState.setMainSliding(true);
        }
    }

    int curret = 0;

    //修改标题
    public void changePage(int cur) {
        changeStatue(texts.get(cur), views.get(cur));
        binding.vpModule.setCurrentItem(cur);
        curret = cur;
    }

    public void changeStatue(TextView tv, View view) {
        for (TextView textView : texts) {
            textView.setTextColor(getResources().getColor(R.color.six_white));
            textView.getPaint().setFakeBoldText(false);
        }
        tv.setTextColor(getResources().getColor(R.color.white));

        for (View v : views) {
            v.setVisibility(View.INVISIBLE);
        }
        view.setVisibility(View.VISIBLE);
    }

    public void getSTS() {
        HTTPAPI.getInstance().getSTS(new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                if (!StringUtil.isFail(s)) {
                    SpUtils.clear(FamilyPeopleFilesActivity.this);
                    startActivity(new Intent(FamilyPeopleFilesActivity.this, LoginActivity.class));
                    ToastUtil.showToast("登陆过期，请重新登陆");
                } else {
                    final STSCallBackBean bean = GsonUtil.GsonToBean(s, STSCallBackBean.class);
                    Runnable runnable = new Runnable() {
                        @Override
                        public void run() {
                            OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(
                                    bean.getData().getAccessKeyId(),
                                    bean.getData().getAccessKeySecret(),
                                    bean.getData().getSecurityToken()) {
                                @Override
                                public OSSFederationToken getFederationToken() {
                                    return super.getFederationToken();
                                }
                            };
                            OSSLog.enableLog();
                            oss = new OSSClient(FamilyPeopleFilesActivity.this, "https://" + bean.getData().getEndPoint(),
                                    credentialProvider, FApplication.getInstance().getClientConfiguration());
                            handler.sendEmptyMessage(200);
                        }
                    };
                    BHThreadPool.getInstance().executeTask(runnable);
                }
            }
        });
    }

    private List<LocalMedia> selectList = new ArrayList<>();

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST && data != null) {
                selectList = PictureSelector.obtainMultipleResult(data);
                peopleId = getIntent().getStringExtra("module_relation");
                LogUtil.e("查看" + peopleId + "的详细信息");
                if (TextUtils.isEmpty(peopleId)) {
                    peopleId = "";
                }
                Runnable runnable = () -> {
                    for (LocalMedia media : selectList) {
                        SystemClock.sleep(100);
                        updateService.setInfo(UPDATE_LOAD_HOME, homeId, SpResourceUtil.getToken(),
                                peopleId, media.getPath());
                    }
                };
                BHThreadPool.getInstance().executeTask(runnable);

                if (!selectList.isEmpty()) {
                    if (selectList.get(0).getMimeType() == 1) showHintDialog(1);
                    else showHintDialog(2);
                }
            }
        } else if (resultCode == 101) {
            String path = data.getStringExtra("path");
            LogUtil.e("图片路径-->" + path);
            updateService.setInfo(UPDATE_LOAD_HOME, homeId, SpResourceUtil.getToken(), peopleId, path);

            if (!TextUtils.isEmpty(path)) showHintDialog(1);
        } else if (resultCode == 102) {
            String url = data.getStringExtra("url");
            LogUtil.e("视频路径-->" + url);
            updateService.setInfo(UPDATE_LOAD_HOME, homeId, SpResourceUtil.getToken(), peopleId, url);

            if (!TextUtils.isEmpty(url)) showHintDialog(2);
        } else if (resultCode == 103) {
            ToastUtil.showToast("请检查相机权限");
        }
    }

    public void showHintDialog(int type) {
        JoinQueueDialog dialog = new JoinQueueDialog(FamilyPeopleFilesActivity.this);
        dialog.setOnCompleteListener(type, fileType -> {
            switch (fileType) {
                case 1:
                    RefreshMessageEvent eventPhoto = new RefreshMessageEvent();
                    eventPhoto.setType("detail");
                    eventPhoto.setId("1");
                    EventBus.getDefault().post(eventPhoto);
                    break;
                case 2:
                    RefreshMessageEvent eventVideo = new RefreshMessageEvent();
                    eventVideo.setType("detail");
                    eventVideo.setId("2");
                    EventBus.getDefault().post(eventVideo);
                    break;
            }
        });
        dialog.show();
    }

    //删除家人
    public void removeHomeUser() {
        HTTPAPI.getInstance().removeHomeUser(homeId, bean.getD_id() + "", new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                LogUtil.e("移除家人成功" + s);
                if (!StringUtil.isFail(s)) {
                    StringUtil.showFail(FamilyPeopleFilesActivity.this, s);
                } else {
                    UpdateStatus bean = new UpdateStatus();
                    bean.setStatus("1");
                    bean.setFirst("");
                    bean.setSecond("");
                    bean.setThird("");
                    bean.setForth("");
                    updateStatusDao.insert(bean);

                    RefreshMessageEvent event = new RefreshMessageEvent();
                    event.setType("refresh");
                    EventBus.getDefault().post(event);

                    ToastUtil.showToast("删除成功");
                    finish();
                }
            }
        });
    }

    //获取家信息，更新个人信息
    public void getFamilyDetail() {
        showProgressDialog();
        HTTPAPI.getInstance().getFamilyDetail(homeId, new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                cancelProgressDialog();
                if (!StringUtil.isFail(s)) {
                    StringUtil.showFail(FamilyPeopleFilesActivity.this, s);
                } else {
                    try {
                        FamilyDeatilCallbackBean callbackBean = GsonUtil.GsonToBean(s, FamilyDeatilCallbackBean.class);
                        for (FamilyDeatilCallbackBean.DataBean dataBean : callbackBean.getData()) {
                            for (FamilyDeatilCallbackBean.DataBean.MembersBean membersBean : dataBean.getMembers()) {
                                if (peopleId.equals(membersBean.getD_id() + "")) {
                                    d_id = membersBean.getD_id() + "";
                                    if (1 == membersBean.getD_is_admin()) {
                                        binding.llModuleCallPhone.setVisibility(View.GONE);
                                    }
                                    setActInfo(membersBean);
                                    bean = membersBean;
                                    binding.setBean(membersBean);
                                }
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                cancelProgressDialog();
                LogUtil.e("获取家详情失败-->" + e.getMessage());
            }
        });
    }

    public void getHomeFileTotal() {
        HTTPAPI.getInstance().getHomeFileTotal(peopleId, new StringCallback() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onSuccess(String s, Call call, Response response) {
                if (!StringUtil.isFail(s)) {
                    StringUtil.showFail(FamilyPeopleFilesActivity.this, s);
                } else {
                    FamilyFileTotalBean bean = GsonUtil.GsonToBean(s, FamilyFileTotalBean.class);
                    for (FamilyFileTotalBean.DataBean dataBean : bean.getData()) {
                        if (dataBean.getFile_type() == 1) {
                            binding.tvModulePhoto.setText("照片" + dataBean.getNum());
                        } else if (2 == dataBean.getFile_type()) {
                            binding.tvModuleVideo.setText("视频" + dataBean.getNum());
                        } else if (4 == dataBean.getFile_type()) {
                            binding.tvModuleText.setText("文本" + dataBean.getNum());
                        }
                    }

                }
            }
        });
    }

    public void startInvita(String id) {
        HTTPAPI.getInstance().startInvita(id, new StringCallback() {
            @Override
            public void onSuccess(String s, Call call, Response response) {
                LogUtil.e("分享成功" + s);
                if (!StringUtil.isFail(s)) {
                    StringUtil.showFail(FamilyPeopleFilesActivity.this, s);
                } else {
                    InviteCallbackBean inner = GsonUtil.GsonToBean(s, InviteCallbackBean.class);
                    String htmlUrl = "http://home.zzwisdom.com/demo/index/share/invite_id/" + inner.getData().getInvite_id();

                    ShareDialog dialog = new ShareDialog(FamilyPeopleFilesActivity.this, "invite");
                    dialog.show();
                    dialog.setOnShareStypeClickListener(style -> {
                        UMWeb web = new UMWeb(htmlUrl);
                        web.setTitle("邀请" + bean.getD_name() + "进入家");
                        web.setDescription("邀请家庭成员");
                        web.setThumb(new UMImage(FamilyPeopleFilesActivity.this, R.mipmap.ic_launcher));

                        switch (style) {
                            case "Wx":
                                new ShareAction(FamilyPeopleFilesActivity.this)
                                        .setPlatform(SHARE_MEDIA.WEIXIN)
                                        .withText("河南传家宝")
                                        .withMedia(web)
                                        .share();
                                break;
                            case "QQ":
                                new ShareAction(FamilyPeopleFilesActivity.this)
                                        .setPlatform(SHARE_MEDIA.QQ)
                                        .withText("河南传家宝")
                                        .withMedia(web)
                                        .share();
                                break;
                        }
                    });
                }
            }
        });
    }

}
